<template>
  <div>
    <Card class="card clear-float">
      <p class="card-title" slot="title">{{$t('hj8dUI3FgLm0q-SC3Lvus')}}</p>
      <div class="operate-area">
        <!-- <div class="inline-item search-item">
          <Input v-model="agentName" @on-enter="searchTable">
            <span slot="prepend">{{$t('3XCbmVH_U3ZYTtc5eh9SZ')}}</span>
            <Button
              slot="append"
              icon="ios-search"
              @click="searchTable"
            ></Button>
          </Input>
        </div> -->
        <div class="inline-item btn-item">
          <Button type="primary" icon="md-add" @click="addAgent"
            >{{$t('3zYq9oc9QxuD15zQ_NMk2')}}</Button
          >
        </div>
        <!-- <div class="inline-item btn-item">
          <Button type="primary" icon="ios-search" @click="userQuery"
            >{{$t('fcPvSAT-dLcX9XXKCC0zX')}}</Button
          >
        </div> -->
        <!-- <div class="inline-item btn-item">
          <Button type="primary" icon="ios-search" @click="stationQuery"
            >{{$t('0vc_V1-wrLIANNTQ1p9Nb')}}</Button
          >
        </div> -->
      </div>
      <Table
        highlight-row
        :loading="loading"
        :columns="columns"
        :data="data"
      ></Table>
      <!-- <Page
        class="page-component"
        size="small"
        :total="total"
        show-sizer
        show-elevator
        show-total
        :current.sync="current"
        :page-size="pageSize"
        :page-size-opts="pageSizeOpts"
        @on-change="changePage"
        @on-page-size-change="changePageSize"
      ></Page> -->
    </Card>
    <Modal
      v-model="formModal"
      :title="formTitle"
      footer-hide
      :mask-closable="false"
    >
      <form-info
        :status="status"
        :data="formData"
        :rules="rules"
        @success="success"
        @fail="fail"
        @close="close"
        @open="open"
      />
    </Modal>
  </div>
</template>

<script>
import { getAgentTableData, deleteAgent } from '@/api/data2'
import FormInfo from './components/agent_form_info'
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapMutations } = createNamespacedHelpers('agent')

export default {
  name: 'agent_info',
  components: {
    FormInfo
  },
  data () {
    return {
      agentName: '',
      loading: false,
      formModal: false,
      status: 'new',
      formData: {
        name: '',
        type: '',
        address: '',
        tel1: '',
        tel2: '',
        person: '',
        pictures: '',
        remark: ''
      },
      rules: {
        name: [{ required: true, message: this.$t('_-lv23N740OG1YfhrHybp'), trigger: 'blur' }],
        type: [{ required: true, message: this.$t('DRSf8G6kWyY02RjPR49pB'), trigger: 'blur' }],
        address: [{ required: true, message: this.$t('DhqXbSAdaCurEIFJ3M_vm'), trigger: 'blur' }],
        tel1: [
          { required: true, message: this.$t('tH6fqASrsycMnb6nj4n21'), trigger: 'blur' },
          {
            required: true,
            message: this.$t('90Cc1VMNr19_iHZ-lgqkY'),
            trigger: 'blur',
            validator: (rule, value) => {
              // 限定为数字，加减号，空格，逗号就可以了，不一定就一个号
              const reg = /[0-9,+\-\s]/
              const list = value.split('')
              let flag = true
              _.forEach(list, l => {
                flag = reg.test(l)
                return flag
              })
              return flag
            }
          }
        ],
        person: [{ required: true, message: this.$t('7thw-wIo--ujxHX5V6eYl'), trigger: 'blur' }]
      },
      columns: [
        {
          title: this.$t('3XCbmVH_U3ZYTtc5eh9SZ'),
          key: 'name',
          width: 200
        },
        {
          title: this.$t('GHvQ9hffCeEL-1pKeULeU'),
          key: 'type',
          width: 140
        },
        {
          title: this.$t('pdkLl0ySj8ba2tm3KR6vq'),
          key: 'address',
          width: 220
        },
        {
          title: this.$t('7JAmVO9o-WPbw9KhjRXPV'),
          key: 'tel1',
          width: 150
        },
        {
          title: this.$t('qC0-FwdnPgSlDRAnzn7fz'),
          key: 'person',
          width: 150
        },
        {
          title: this.$t('R50mHX0LambJk39x8cmq6'),
          key: 'remark',
          width: 200
        },
        {
          title: this.$t('Ty1ns2epHIaihi82jwUfc'),
          width: 280,
          fixed: 'right',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                    icon: 'ios-search'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      const item = this.data[params.index]
                      this.setSelections([item])
                      this.userQuery()
                    }
                  }
                },
                this.$t('qyc357Je2Q3ZMuH1yd04x')
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'warning',
                    size: 'small',
                    icon: 'ios-create'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.editItem(params.index)
                    }
                  }
                },
                this.$t('3cH_U2GeBUW1V74W8oDNv')
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small',
                    icon: 'ios-trash'
                  },
                  on: {
                    click: () => {
                      this.deleteItem(params.index)
                    }
                  }
                },
                this.$t('hND4KLgCabT6swtTJBIUf')
              )
            ])
          }
        }
      ],
      data: [],
      total: 10,
      current: 1,
      pageSize: 5,
      pageSizeOpts: [5, 10, 15, 20]
    }
  },
  created () {
    this.queryTable()
  },
  computed: {
    ...mapState(['selections', 'allAgents']),
    formTitle () {
      return (this.status === 'new' ? this.$t('N8xdbBoV-d6Vc33tKrGGm') : this.$t('3cH_U2GeBUW1V74W8oDNv')) + this.$t('hj8dUI3FgLm0q-SC3Lvus')
    }
  },
  methods: {
    ...mapMutations(['setSelections', 'setAllAgents']),
    userQuery () {
      if (this.selections.length > 0) {
        this.$router.push({
          name: 'user_query',
          params: {
            id: this.selections[0].id + ''
          }
        })
      } else {
        this.$Message.warning(this.$t('QKLjZ1o2DdfPm2yqARZFW'))
      }
    },
    stationQuery () {
      if (this.selections.length > 0) {
        this.$router.push({
          name: 'charge_station'
        })
      } else {
        this.$Message.warning(this.$t('QKLjZ1o2DdfPm2yqARZFW'))
      }
    },
    // selectionChangeHandler (selection) {
    //   console.log(selection)
    //   this.setSelections([selection])
    // },
    searchTable () {
      this.queryTable()
    },
    async queryTable ({
      current = this.current,
      pageSize = this.pageSize,
      search = this.agentName
    } = {}) {
      this.loading = true
      const { code, data, desc } = await getAgentTableData({
        // pageSize,
        // current,
        search
      })
      if (code == 200) {
        this.data = data.datalist || []
        this.setAllAgents(_.cloneDeep(this.data))
        // this.total = res.total
      } else {
        this.$Message.error(desc)
      }
      this.loading = false
    },
    changePage (num) {
      this.current = num
      this.queryTable()
    },
    changePageSize (num) {
      this.pageSize = num
      this.queryTable()
    },
    addAgent () {
      this.formData = {
        name: '',
        type: '',
        address: '',
        tel1: '',
        tel2: '',
        person: '',
        pictures: '',
        remark: ''
      }
      this.status = 'new'
      this.formModal = true
    },
    cancel () {
      this.formModal = false
    },
    editItem (index) {
      const item = this.data[index]
      this.formData = {
        ...item
      }
      this.status = 'edit'
      this.editIndex = index
      this.formModal = true
    },
    deleteItem (index) {
      this.$Modal.confirm({
        title: this.$t('oiW2WYZoyJSt3j7yCy10e'),
        content: this.$t('KePcPzUJR7hEB6lp4nEtV'),
        onOk: async () => {
          // this.data.splice(index, 1)
          const { code, desc } = await deleteAgent({
            name: this.data[index].name
          })
          if (code == 200) {
            this.$Message.success(this.$t('hWGIgDqZtmSWFd9gU3Ya7'))
            this.queryTable()
          } else {
            this.$Message.error(desc)
          }
        }
      })
    },
    success (desc) {
      if (this.status === 'new') {
        this.$Message.success(desc || this.$t('38AWpi9C1Z7eLtpj1TEfD'))
      } else {
        this.$Message.success(desc || this.$t('qDM1Ic0NDNp4weHsjQ4sN'))
      }
      this.formModal = false
      this.queryTable()
    },
    fail (msg) {
      this.formModal = false
      this.$Message.error(msg)
    },
    close () {
      this.formModal = false
    },
    open () {
      this.formModal = true
    }
  }
}
</script>
